package com.haust.community.service;

import com.haust.community.mapper.LoginTicketMapper;
import com.haust.community.mapper.UserMapper;
import com.haust.community.pojo.LoginTicket;
import com.haust.community.pojo.User;
import com.haust.community.utils.CommunityConstant;
import com.haust.community.utils.CommunityUtil;
import com.haust.community.utils.MailClient;
import com.haust.community.utils.RedisKeyUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: csp1999
 * @Date: 2020/11/24/9:02
 * @Description: UserService(使用Redis缓存数据)
 */
@Service
public class UserService implements CommunityConstant {

    @Autowired
    private UserMapper userMapper;

    // 不推荐再使用，该接口功能被redis替代
    @Autowired
    private LoginTicketMapper loginTicketMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private MailClient mailClient;// 邮件客户端

    @Autowired
    private TemplateEngine templateEngine;// thymleaf 模板引擎

    @Value("${community.path}")
    private String path;// 本机域名 http://csp1999.natapp1.cc

    @Value("${server.servlet.context-path}")
    private String contextPath;// 项目名称

    /**
     * 获取某个用户所具备的权限的集合
     * @param userId
     * @return
     */
    public Collection<? extends GrantedAuthority> getAuthorities(int userId) {
        // 根据用户id 查询用户信息
        User user = this.findUserById(userId);

        // 权限集合
        List<GrantedAuthority> list = new ArrayList<>();
        list.add(new GrantedAuthority() {
            @Override
            public String getAuthority() {
                // 根据从数据库查到的用户身份类型 type 来判别权限
                switch (user.getType()) {
                    case 1:
                        return AUTHORITY_ADMIN;// 权限: 管理员
                    case 2:
                        return AUTHORITY_MODERATOR;// 权限: 版主
                    default:
                        return AUTHORITY_USER;// 权限: 普通用户
                }
            }
        });
        return list;
    }

    /**
     * 根据id查询用户信息
     *
     * @param id
     * @return
     */
    public User findUserById(int id) {
        //return userMapper.selectById(id);
        // 先从缓存中获取
        User user = getCache(id);
        if (user == null) {
            // 缓存中没有去初始化缓存数据
            user = initCache(id);
        }
        return user;
    }

    /**
     * 新用户注册
     *
     * @param user
     * @return
     */
    public Map<String, Object> register(User user) {
        Map<String, Object> map = new HashMap<>();

        // 空值处理
        if (user == null) {
            throw new IllegalArgumentException("参数不能为空!");
        }
        if (StringUtils.isBlank(user.getUsername())) {
            map.put("usernameMsg", "账号不能为空!");
            return map;
        }
        if (StringUtils.isBlank(user.getPassword())) {
            map.put("passwordMsg", "密码不能为空!");
            return map;
        }
        if (StringUtils.isBlank(user.getEmail())) {
            map.put("emailMsg", "邮箱不能为空!");
            return map;
        }

        // 验证账号
        User u = userMapper.selectByName(user.getUsername());
        if (u != null) {
            map.put("usernameMsg", "该账号已存在!");
            return map;
        }

        // 验证邮箱
        u = userMapper.selectByEmail(user.getEmail());
        if (u != null) {
            map.put("emailMsg", "该邮箱已被注册!");
            return map;
        }

        // 注册用户
        user.setSalt(CommunityUtil.generateUUID().substring(0, 5));
        user.setPassword(CommunityUtil.md5(user.getPassword() + user.getSalt()));
        user.setType(0);
        user.setStatus(0);
        user.setActivationCode(CommunityUtil.generateUUID());
        user.setHeaderUrl(String.format("http://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000)));
        user.setCreateTime(new Date());
        userMapper.insertUser(user);

        // 激活邮件发送
        Context context = new Context();// org.thymeleaf.context.Context 包下
        context.setVariable("email", user.getEmail());

        // http://csp1999.natapp1.cc/community/activation/用户id/激活码
        String url = path + contextPath + "/activation/" + user.getId() + "/" + user.getActivationCode();
        context.setVariable("url", url);
        String content = templateEngine.process("/mail/activation", context);

        // 由于邮件发送速度较慢，为了用户体验方便，这里采用多线程的方式
        // 单独分一个线程去发送邮件，不影页面响用户响应！
        Thread thread = new Thread() {
            public void run() {
                mailClient.sendMail(user.getEmail(), "激活账号", content);
            }
        };
        thread.start();

        return map;
    }

    /**
     * 登录
     *
     * @param username
     * @param password
     * @param expiredSeconds 过期时间,单位:秒
     * @return
     */
    public Map<String, Object> login(String username,
                                     String password, int expiredSeconds) {
        Map<String, Object> map = new HashMap<>();

        // 空值处理
        if (StringUtils.isBlank(username)) {
            map.put("usernameMsg", "账号不能为空!");
            return map;
        }
        if (StringUtils.isBlank(password)) {
            map.put("passwordMsg", "密码不能为空!");
            return map;
        }

        // 验证账号
        User user = userMapper.selectByName(username);
        if (user == null) {
            map.put("usernameMsg", "该账号不存在!");
            return map;
        }

        // 验证状态
        if (user.getStatus() == 0) {
            map.put("usernameMsg", "该账号未激活!");
            return map;
        }

        // 验证密码
        password = CommunityUtil.md5(password + user.getSalt());
        if (!user.getPassword().equals(password)) {
            map.put("passwordMsg", "密码不正确!");
            return map;
        }

        // 生成登录凭证
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setUserId(user.getId());// 用户id
        loginTicket.setTicket(CommunityUtil.generateUUID());// 登录凭证
        loginTicket.setStatus(0);// 凭证状态
        // 凭证过期时间: 当前时间毫秒数 + 登录凭证有效持续时间毫秒数
        loginTicket.setExpired(new Date(System.currentTimeMillis() + expiredSeconds * 1000));
        //loginTicketMapper.insertLoginTicket(loginTicket);

        // 获取登录的凭证的key
        String ticketKey = RedisKeyUtil.getTicketKey(loginTicket.getTicket());
        redisTemplate.opsForValue().set(ticketKey, loginTicket);

        map.put("ticket", loginTicket.getTicket());
        return map;
    }

    /**
     * 退出登录
     *
     * @param ticket
     */
    public void logout(String ticket) {
        //loginTicketMapper.updateStatus(ticket, 1);
        // 获取登录的凭证的key
        String ticketKey = RedisKeyUtil.getTicketKey(ticket);

        LoginTicket loginTicket = (LoginTicket) redisTemplate.opsForValue().get(ticketKey);
        // 使该登录凭证的状态失效(status = 1)
        loginTicket.setStatus(1);
        redisTemplate.opsForValue().set(ticketKey, loginTicket);
    }

    /**
     * 根据凭证查询
     *
     * @param ticket 登录凭证
     * @return
     */
    public LoginTicket findLoginTicket(String ticket) {
        //return loginTicketMapper.selectByTicket(ticket);
        String ticketKey = RedisKeyUtil.getTicketKey(ticket);
        return (LoginTicket) redisTemplate.opsForValue().get(ticketKey);
    }

    /**
     * 修改头像
     *
     * @param userId    用户id
     * @param headerUrl 头像url
     * @return
     */
    public int updateHeader(int userId, String headerUrl) {
        //return userMapper.updateHeader(userId, headerUrl);
        int rows = userMapper.updateHeader(userId, headerUrl);
        // 修改用户数据后清理缓存
        clearCache(userId);
        return rows;
    }

    /**
     * 用户激活
     *
     * @param userId 用户id
     * @param code   激活码
     * @return
     */
    public int activation(int userId, String code) {
        User user = userMapper.selectById(userId);
        if (user.getStatus() == 1) {
            return ACTIVATION_REPEAT;
        } else if (user.getActivationCode().equals(code)) {
            userMapper.updateStatus(userId, 1);
            // 修改用户信息后清空缓存数据
            clearCache(userId);
            return ACTIVATION_SUCCESS;
        } else {
            return ACTIVATION_FAILURE;
        }
    }

    /**
     * 根据用户名查询用户信息
     *
     * @param username
     * @return
     */
    public User findUserByName(String username) {
        return userMapper.selectByName(username);
    }

    // 1.优先从缓存中取值
    private User getCache(int userId) {
        String redisKey = RedisKeyUtil.getUserKey(userId);
        return (User) redisTemplate.opsForValue().get(redisKey);
    }

    // 2.取不到时初始化缓存数据
    private User initCache(int userId) {
        User user = userMapper.selectById(userId);
        String redisKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.opsForValue().set(redisKey, user, 3600, TimeUnit.SECONDS);
        return user;
    }

    // 3.数据变更时清除缓存数据
    private void clearCache(int userId) {
        String redisKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.delete(redisKey);
    }
}
